<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<div id="app">
  {{msg}}
  <hr>
  <ul>
    <li v-for="item in list">
      <input type="checkbox" v-model="item.ck"> {{item.id}}:==={{item.name}}==={{item.price}}元==={{item.num}}双 ===
      <button @click="add(item.id)">+</button>===<button @click="del(item.id)">-</button>
    </li>
  </ul>
  <input type="checkbox" v-model="ckAll"> 总数:{{totalNum}}双 总价:{{totalPrice}}元
</div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.7.14/vue.min.js"></script>
<script>
  const vu = new Vue({
    el: "#app",
    data: {
      msg: 'hello vue',
      //读取本地数据,有则读取无则自己存
      list: JSON.parse(localStorage.getItem('list')) || [{
        id: 1,
        name: '阿迪',
        price: 30,
        num: 3,
        ck: false
      }, {
        id: 2,
        name: '耐克',
        price: 20,
        num: 4,
        ck: false
      }, {
        id: 3,
        name: '安踏',
        price: 10,
        num: 2,
        ck: false
      }],
      // ckAll: '',
      // total: 20


    },
    methods: {
      add (id) {
        const res = this.list.find(ele => {
          return ele.id == id
        })
        if (res.num <= 10) {
          res.num++
          // this.list.num = res.num
        }

      },
      del (id) {
        const res =
          this.list.find(ele => {
            return ele.id == id
          })
        if (res.num >= 1) {
          res.num--
          // this.list.num = res.num
        }


      }

    },
    //全选反选功能,计算属性的完整写法
    computed: {
      ckAll: {
        // 通过小框全选选择全选框
        get () {
          return this.list.every(ele => {
            return ele.ck //ele.ck===true,可以省略true,因为点中按钮就是true
          })
        },
        //newVal是全选框的选中状态,根据全选框反选小选框
        set (newVal) {
          this.list.forEach(element => {
            element.ck = newVal
          });
        }
      },
      totalNum () {
        // 求和用reduce,
        // 条件判断: 选择才累加不选中则不累加
        return this.list.reduce((sum, item) => {
          if (item.ck) {
            //选中需要累加
            return sum + item.num
          } else {
            //没选中不需要累加
            return sum
          }
        }, 0)

      },
      //计算选中的总价,选中的num*price
      totalPrice () {
        return this.list.reduce((sum, item) => {
          if (item.ck) {
            return sum + item.num * item.price
          } else {
            return sum

          }
        }, 0)

      }
    },
    //本地持久化 ,监视数据变化 watch
    watch: {
      //需要深度监听
      list: {

        handler (newVal) {
          //保存数据到本地
          localStorage.setItem('list', JSON.stringify(newVal))

        },
        deep: true,
        immediate: true
      },


    }


  })
</script>






</body>

</html>